<template>
	<el-dialog :title="props.title" :model-value="props.show" @closed="emitClose">
		<el-upload
			ref="uploadRef"
			:multiple="true"
			:action="uploadURL"
			v-loading="loading"
			:drag="width > 800"
			:file-list="fileList"
			:accept="props.accept"
			:on-change="emitChange"
			class="upload-in-dialog"
			:on-success="uploadResponse"
			:http-request="customHttpPost"
		>
			<el-icon color="#409EFC" :size="60"> <upload-filled /> </el-icon>
			<div class="el-upload__text" v-if="width > 800">
				拖动文件至此 <em>点击上传</em>
			</div>
			<div class="el-upload__text" v-else>点击上传</div>
		</el-upload>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="emitClose">关闭</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { defineEmits, ref } from "vue";
import { useWindow } from "@/utils/useWindow";
import { resolveURL } from "@/utils/useRequest";
import { UploadFilled } from "@element-plus/icons-vue";
import type {
	UploadFile,
	ElUploadRequestOptions,
} from "element-plus/es/components/upload/src/upload.type";
import { useCustomHttpPost } from "@/utils/upload";

const loading = ref(false);
const { width } = useWindow();
const fileList = ref([] as UploadFile[]);
const uploadURL = resolveURL("media/upload");
const emit = defineEmits(["close", "changeFiles", "complete"]);

const props = defineProps({
	show: {
		type: Boolean,
		default: false,
	},
	title: {
		type: String,
		default: "",
	},
	mediatype: {
		type: String,
		default: "AUDIO",
	},
	accept: {
		type: String,
		default: "",
	},
	setBtnLoading: {
		type: Function,
		default: () => {},
	},
	setBoxShow: {
		type: Function,
		default: () => {},
	},
});

function emitClose() {
	emit("close");
}

function emitChange(file: UploadFile, allfileList: UploadFile[]) {
	const len = 16;
	if (file.name.length > len) {
		file.name = file.name.slice(0, len) + "...";
	}

	fileList.value.push(file);
	if (fileList.value.length > 1) {
		fileList.value = fileList.value.slice(-1);
	}
	emit("changeFiles", file, allfileList);
}

function uploadResponse(res: any) {
	emit("complete", res);
	loading.value = false;
	props.setBtnLoading(loading.value);
}

function customHttpPost(req: ElUploadRequestOptions) {
	loading.value = true;
	props.setBoxShow(false);
	props.setBtnLoading(loading.value);
	return useCustomHttpPost(req, props.mediatype);
}
</script>

<style lang="less">
.dialog-footer button:first-child {
	margin-right: 10px;
}

.el-dialog {
	width: 600px;

	@media screen and (max-width: 800px) {
		width: 300px;
	}

	@media screen and (max-width: 476px) {
		width: 260px;
	}

	.el-upload-dragger {
		width: 100%;
		padding: 50px;
		@media screen and (max-width: 800px) {
			padding: 20px;
		}
	}
}
</style>
